package com.tian.clothing.global;

import java.util.ArrayList;

import com.tian.clothing.base.BaseActivity;
import com.tian.clothing.constant.GlobalConstant;
import com.tian.clothing.entity.TaskEntity;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;

/**
 * @ClassName: ClothingApplication
 * @Description: 全局变量
 * @author: dreamfutureba@gmail.com
 * @date: 2013年11月21日 下午3:48:15
 */
public class ClothingApplication extends Application {
	private static final String TAG = ClothingApplication.class.getSimpleName();

	private static ClothingApplication appInstance;

	private ArrayList<BaseActivity> mBaseActivityList;// 当前未关闭的界面列表
	public Activity mLastActivity = null;// 栈顶的Activity

	public static ClothingApplication getApp() {
		return appInstance;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		appInstance = this;

		mBaseActivityList = new ArrayList<BaseActivity>();
	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
	}

	// ==============Activity的管理==================================
	/**
	 * 添加AbsBaseActivity
	 * 
	 * @param ac
	 */
	public void addActivity(BaseActivity ac) {
		if (!mBaseActivityList.contains(ac)) {
			mBaseActivityList.add(ac);
		}
	}

	/**
	 * 从列表中删除指定的AbsBaseActivity
	 * 
	 * @param ac
	 */
	public void removeActivity(BaseActivity ac) {
		mBaseActivityList.remove(ac);
	}

	/**
	 * 删除所有的BaseActivity
	 */
	public void removeAllBaseActivity() {
		mBaseActivityList.clear();
	}

	/**
	 * 使用广播实现关闭所有的Activity
	 */
	public void closeAllActivity() {
		Intent intent = new Intent();
		intent.setAction(GlobalConstant.CLOSE_ALL_ACTIVITY);
		sendBroadcast(intent);
	}

	// ===============Finish Activity for Special=======================

	/**
	 * Finish 系统Activity Stack中指定Activity前面的所有Activity,包括自己。
	 * 
	 * @param activityName
	 */
	public void destoryToActivity(String activityName) {
		Activity ac = null;
		for (int i = mBaseActivityList.size() - 1; i >= 0; i--) {
			ac = mBaseActivityList.get(i);

			if (ac.getClass().getSimpleName().equals(activityName)) {
				ac.finish();
				break;
			} else {
				ac.finish();
			}
		}
	}

	/**
	 * Finish 所有的Activity界面
	 */
	public void destoryAllActivity() {
		Activity ac = null;
		for (int i = mBaseActivityList.size() - 1; i >= 0; i--) {
			ac = mBaseActivityList.get(i);
			ac.finish();
		}
	}

	/**
	 * 退出应用程序
	 */
	public void exitApp() {
		closeAllActivity();
		// stopService();
		android.os.Process.killProcess(android.os.Process.myPid());
	}
}
